using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;

namespace OrderingSystem.API.Controllers
{
    [Authorize]
    [ApiController]
    [Route("dingdan")]
    public class OrderController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly INotificationService _notificationService;
        private static readonly SemaphoreSlim _orderNumberLock = new SemaphoreSlim(1, 1);

        public OrderController(
            ApplicationDbContext context,
            INotificationService notificationService)
        {
            _context = context;
            _notificationService = notificationService;
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<IEnumerable<OrderDto>>> GetOrders([FromQuery] string status = null)
        {
            var query = _context.Orders.AsQueryable();
            
            if (!string.IsNullOrEmpty(status))
            {
                query = query.Where(o => o.sfsh == status);
            }
            
            var orders = await query
                .OrderByDescending(o => o.addtime)
                .Select(o => new OrderDto
                {
                    Id = o.id,
                    OrderNumber = o.dingdanbianhao,
                    UserName = o.yonghuming,
                    UserId = o.userid,
                    Status = o.sfsh,
                    PaymentStatus = o.ispay,
                    Address = o.songcandizhi,
                    Remarks = o.shhf,
                    TotalAmount = GetTotalAmountStatic(o.zongjine),
                    Items = o.caipinmingcheng,
                    AddTime = o.addtime
                })
                .ToListAsync();
            
            return Ok(orders);
        }

        private static decimal GetTotalAmountStatic(string zongjine)
        {
            if (decimal.TryParse(zongjine, out var amount))
            {
                return amount;
            }
            return 0;
        }

        private decimal GetTotalAmount(string zongjine)
        {
            return GetTotalAmountStatic(zongjine);
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<OrderDto>> GetOrder(long id)
        {
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }

            var orderDto = new OrderDto
            {
                Id = order.id,
                OrderNumber = order.dingdanbianhao,
                UserName = order.yonghuming,
                UserId = order.userid,
                Status = order.sfsh,
                PaymentStatus = order.ispay,
                Address = order.songcandizhi,
                Remarks = order.shhf,
                TotalAmount = GetTotalAmountStatic(order.zongjine),
                Items = order.caipinmingcheng,
                AddTime = order.addtime
            };

            return Ok(orderDto);
        }

        /// <summary>
        /// 获取订单详情 - 兼容前端info接口
        /// </summary>
        [HttpGet("info/{id}")]
        public async Task<ActionResult<OrderDto>> GetOrderInfo(long id)
        {
            try
            {
                var order = await _context.Orders
                    .Include(o => o.User)
                    .FirstOrDefaultAsync(o => o.id == id);

                if (order == null)
                {
                    return NotFound(new { code = 1, msg = "订单不存在" });
                }

                var orderDto = new OrderDto
                {
                    Id = order.id,
                    OrderNumber = order.dingdanbianhao,
                    UserName = order.User?.yonghuming ?? string.Empty,
                    UserId = order.User?.id ?? 0,
                    Status = order.sfsh,
                    PaymentStatus = order.ispay,
                    Address = order.songcandizhi,
                    Remarks = order.shhf,
                    TotalAmount = GetTotalAmount(order.zongjine),
                    Items = order.caipinmingcheng,
                    AddTime = order.addtime
                };

                return Ok(new { code = 0, data = orderDto });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 1, msg = $"获取订单详情失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取用户订单
        /// </summary>
        [HttpGet("user")]
        public async Task<ActionResult<IEnumerable<OrderDto>>> GetUserOrders()
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            
            var orders = await _context.Orders
                .Where(o => o.userid == userId)
                .OrderByDescending(o => o.addtime)
                .Select(o => new OrderDto
                {
                    Id = o.id,
                    OrderNumber = o.dingdanbianhao,
                    UserName = o.yonghuming,
                    UserId = o.userid,
                    Status = o.sfsh,
                    PaymentStatus = o.ispay,
                    Address = o.songcandizhi,
                    Remarks = o.shhf,
                    TotalAmount = GetTotalAmountStatic(o.zongjine),
                    Items = o.caipinmingcheng,
                    AddTime = o.addtime
                })
                .ToListAsync();
            
            return Ok(orders);
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        [HttpPost("add")]
        [Authorize]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderModel model)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            var user = await _context.Users.FindAsync(userId);
            if (user == null)
            {
                return BadRequest(new { message = "用户不存在" });
            }

            var order = new Order
            {
                dingdanbianhao = GenerateOrderNumber(),
                caipinmingcheng = model.Items,
                shuliang = 1, // 默认数量
                zongjine = model.TotalAmount.ToString(), // 将 decimal 转换为字符串
                xiadanshijian = DateTime.Now,
                songcandizhi = model.Address,
                yonghuming = user.yonghuming,
                lianxidianhua = user.lianxidianhua,
                userid = userId,
                addtime = DateTime.Now,
                shhf = model.Remarks // 使用 shhf 字段存储备注信息
            };

            _context.Orders.Add(order);
            await _context.SaveChangesAsync();

            // 发送新订单通知
            await _notificationService.SendNewOrderAsync(order);

            return Ok(new { message = "订单创建成功", orderId = order.id });
        }

        /// <summary>
        /// 更新订单状态
        /// </summary>
        [HttpPost("status/{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> UpdateOrderStatus(long id, [FromBody] UpdateOrderStatusModel model)
        {
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound(new { message = "订单不存在" });
            }

            order.sfsh = model.Status;
            order.shhf = model.Remarks;
            
            await _context.SaveChangesAsync();
            
            // 发送订单状态变更通知
            await _notificationService.SendOrderStatusChangedAsync(order);
            
            return Ok(new { message = "订单状态更新成功" });
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        [HttpPost("cancel/{id}")]
        [Authorize]
        public async Task<IActionResult> CancelOrder(long id)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            var order = await _context.Orders.FindAsync(id);
            
            if (order == null)
            {
                return NotFound(new { message = "订单不存在" });
            }
            
            if (order.userid != userId)
            {
                return Forbid();
            }
            
            // 只有未审核的订单才能取消
            if (order.sfsh != "否")
            {
                return BadRequest(new { message = "已审核的订单不能取消" });
            }
            
            order.sfsh = "已取消";
            await _context.SaveChangesAsync();
            
            // 发送订单取消通知
            await _notificationService.SendOrderCancelledAsync(order);
            
            return Ok(new { message = "订单已取消" });
        }

        /// <summary>
        /// 生成订单号
        /// </summary>
        private string GenerateOrderNumber()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999).ToString();
        }

        /// <summary>
        /// 支付订单
        /// </summary>
        [HttpPost("pay/{id}")]
        [Authorize]
        public async Task<IActionResult> UpdatePaymentStatus(long id)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound(new { code = 1, msg = "订单不存在" });
            }

            if (order.userid != userId && !User.IsInRole("Admin"))
            {
                return Forbid();
            }

            if (order.ispay == "已支付")
            {
                return BadRequest(new { code = 1, msg = "订单已支付" });
            }

            order.ispay = "已支付";
            order.addtime = DateTime.Now;

            await _context.SaveChangesAsync();
            await _notificationService.SendOrderStatusChangedAsync(order);

            return Ok(new { code = 0, msg = "支付成功" });
        }

        /// <summary>
        /// 分页获取订单
        /// </summary>
        [HttpGet("page")]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrdersPage(
            [FromQuery] int page = 1, 
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "addtime",
            [FromQuery] string order = "desc",
            [FromQuery] string status = null)
        {
            try
            {
                var query = _context.Orders.Include(o => o.User).AsQueryable();

                // 筛选状态
                if (!string.IsNullOrEmpty(status))
                {
                    query = query.Where(o => o.sfsh == status);
                }

                // 排序
                if (sort == "addtime")
                {
                    query = order == "desc" 
                        ? query.OrderByDescending(o => o.addtime)
                        : query.OrderBy(o => o.addtime);
                }
                else if (sort == "id")
                {
                    query = order == "desc" 
                        ? query.OrderByDescending(o => o.id)
                        : query.OrderBy(o => o.id);
                }

                var totalCount = await query.CountAsync();
                var orders = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToListAsync();

                // 修改返回格式以匹配前端期望的字段名
                var orderList = orders.Select(o => new OrderListItem
                {
                    id = o.id,
                    dingdanbianhao = o.dingdanbianhao,
                    caipinmingcheng = o.caipinmingcheng,
                    caipinfenlei = o.caipinfenlei,
                    tupian = o.tupian,
                    caipinjiage = o.caipinjiage,
                    shuliang = o.shuliang,
                    zongjine = o.zongjine,
                    xiadanshijian = o.xiadanshijian,
                    songcandizhi = o.songcandizhi,
                    yonghuming = o.yonghuming,
                    lianxidianhua = o.lianxidianhua,
                    sfsh = o.sfsh,
                    shhf = o.shhf,
                    ispay = o.ispay,
                    userid = o.userid
                }).ToList();

                return Ok(new
                {
                    code = 0,
                    data = new
                    {
                        total = totalCount,
                        pageSize = limit,
                        totalPage = (int)Math.Ceiling((double)totalCount / limit),
                        currPage = page,
                        list = orderList
                    }
                });
            }
            catch (Exception ex)
            {
                // 记录异常
                Console.WriteLine($"获取订单分页数据时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                
                // 返回错误响应
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }
    }

    public class OrderDto
    {
        public long Id { get; set; }
        public string OrderNumber { get; set; }
        public string UserName { get; set; }
        public long UserId { get; set; }
        public string Status { get; set; }
        public string PaymentStatus { get; set; }
        public string Address { get; set; }
        public string Remarks { get; set; }
        public decimal TotalAmount { get; set; }
        public string Items { get; set; }
        public DateTime AddTime { get; set; }
    }

    public class CreateOrderModel
    {
        public string Address { get; set; }
        public string Remarks { get; set; }
        public decimal TotalAmount { get; set; }
        public string Items { get; set; }
    }

    public class UpdateOrderStatusModel
    {
        public string Status { get; set; }
        public string TableNumber { get; set; }
        public string Remarks { get; set; }
    }

    public class OrderListItem
    {
        public long id { get; set; }
        public string dingdanbianhao { get; set; }
        public string caipinmingcheng { get; set; }
        public string caipinfenlei { get; set; }
        public string tupian { get; set; }
        public int? caipinjiage { get; set; }
        public int shuliang { get; set; }
        public string zongjine { get; set; }
        public DateTime xiadanshijian { get; set; }
        public string songcandizhi { get; set; }
        public string yonghuming { get; set; }
        public string lianxidianhua { get; set; }
        public string sfsh { get; set; }
        public string shhf { get; set; }
        public string ispay { get; set; }
        public long userid { get; set; }
    }
} 